package com.lib.module_base.view;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.lib.module_base.R;

public class CustomDialog extends ProgressDialog {
    private TextView loadDialogTv;
    private String text;
    private boolean cancelable = false;

    public CustomDialog(Context context, String text) {
        super(context, R.style.CustomDialog);
        this.text = text;
    }

    public CustomDialog(Context context, String text, boolean cancelable) {
        super(context, R.style.CustomDialog);
        this.text = text;
        this.cancelable = cancelable;
    }

    public CustomDialog(Context context, int theme) {
        super(context, theme);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(getContext());
    }

    private void init(Context context) {
        //设置不可取消，点击其他区域不能取消，可以抽出去封装供外包设置
        setCancelable(cancelable);
        setCanceledOnTouchOutside(cancelable);
        setContentView(R.layout.layout_dialog);
        loadDialogTv = findViewById(R.id.load_dialog_Tv);
        loadDialogTv.setText(TextUtils.isEmpty(text) ? "请稍候" : text);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getWindow().setAttributes(params);
    }

    public void setLoadDialogText(String text) {
        if (!TextUtils.isEmpty(text))
            loadDialogTv.setText(text);
    }

    @Override
    public void show() {
        Context context = getContext();
        if (context instanceof AppCompatActivity) {
            Activity activity = (Activity) context;
            if (!activity.isDestroyed()) {
                super.show();
            }
        } else {
            super.show();
        }
    }

}
